package com.blogs.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import android.content.Context;
import android.util.Log;

import com.blogs.entity.AppConfig;
import com.blogs.entity.FavFeed;
import com.blogs.entity.MsgEntity;
import com.blogs.tools.MsgCountToast;
import com.blogs.tools.TbFavorite;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GetFavorite {
	public interface IMsgCallBack {
		public void onSuccess(ArrayList<FavFeed> feedList);

		public void onFailed();
	}

	private TbFavorite db;
	private String url = AppConfig.GET_FAVORITE_LINE;
	private IMsgCallBack callback;
	private boolean isCache;
	private boolean isMore;
	private boolean isPull;
	private String since_id;
	private GetMsgTask timeLine;
	private Context context;

	public GetFavorite(Context context, String sid, int page,String since_id,String max_id,Boolean has_new, IMsgCallBack callback) {
		this.callback = callback;
		timeLine = new GetMsgTask(taskCallBack);
		url = url.replace("{0}", sid).replace("{1}", page + "");
		this.since_id=since_id;
		this.context=context;
		isCache=since_id.equals("")&&max_id.equals("")&&!has_new;
		isMore=!max_id.equals("");
		isPull=!since_id.equals("");
		db = new TbFavorite(context);
	}

	public void loadData() {

		if (db.RowCount() > 0 && isCache) {
			callback.onSuccess(db.Select());
			db.DbClose();
		} else {
			timeLine.execute(url);
		}
	}

	private GetMsgTask.onTaskCallBack taskCallBack = new GetMsgTask.onTaskCallBack() {

		public void onSuccess(String result) {
			// TODO Auto-generated method stub

			GsonBuilder builder = new GsonBuilder();
			Gson gson = builder.create();
			MsgEntity<ArrayList<Object>> msg=null;
			try
			{
				msg=gson.fromJson(result,MsgEntity.class);
			}
			catch(Exception e)
			{
				callback.onFailed();
				if(db!=null)
				{
					db.DbClose();
				}
				return;
			}
			if(msg.op.equals(""))
			{
				callback.onFailed();
				if(db!=null)
				{
					db.DbClose();
				}
				return;
			}
			ArrayList<FavFeed> favofeeds=new ArrayList<FavFeed>();
			Iterator<Object> iterator = msg.data.iterator();
			int i=0;
			while (iterator.hasNext()) 
			{
				i++;
				Map<String, Object> objs = (Map<String, Object>) iterator.next();
				FavFeed newsfeed = new FavFeed(objs);
				favofeeds.add(newsfeed);
			}
			if(!isMore)
			{
				db.Delete();
				db.Insert(favofeeds);
			}
			if(isPull)
			{
				int fcount=0;
				for(FavFeed f :favofeeds)
				{
					if(since_id.equals(f.favo_id))
					{
						break;
					}
					fcount++;
				}
				MsgCountToast.ShowToast(context, fcount);
			}
			db.DbClose();
			Log.i("newsfeeds", favofeeds.size()+","+i);
			callback.onSuccess(favofeeds);
		}

		public void onFailed() {
			// TODO Auto-generated method stub
			callback.onFailed();
			Log.i("GetMsgTask", "Failed");
		}
	};
}
